%% 最终的权重因子计算
day = length(trend);
Cap = 1000;
process = zeros(day,3);
process(58,1) = 0;
process(58,2) = 0;
process(58,3) = Cap;
gold_real =  trend(:,3);
gold_pre =   trend(:,4);
bit_real = trend(:,1);
bit_pre = trend(:,2);
gold_holy_pre = trend(:,6);
alldata = [bit_real,gold_real,bit_pre,gold_real];


gold_RATE = 0.01;
BIT_RATE = 0.02;



R0=0.23;% 期望收益率
Rick_w = 10; 

Cvar = zeros(1,3);
W = zeros(1,1);

profits = [];    

for C = 0.01:0.01:0.1
gold_RATE = C ;
BIT_RATE = 2*C;
for i = 59:day-1
        Sentrix = [alldata(i-30:i,1:2);alldata(i+1,3:4)];
        [ww,fval] =  CVaROptimization(Sentrix,[0.5,0.5]*Rick_w,R0,[],0.96,1,-0.1);
        Cvar(i-58,:) = fval(:);
        W(i-58) = ww;
end
% figure
%  plot(Cvar(:,1),'*');hold on ;
%  plot(Cvar(:,2),'*');hold on ;
%  %plot(Cvar(:,3));hold on ;
%  legend('bit','gold');
% figure;
% plot(W);
% mean(W);
% disp("1")

%% 如何对待Cvar 第一种策略 凡是大于1 的都是做异常，根据cvar抛售
maxvar = max(W);

for i = 59:day-1
    j  = i-58; % 对于Cvar的索引
    % 对前一天的价格进行计算
    process(i,1) = process(i-1,1)*(1+ bit_real(i) );

    if(gold_real(i)~=0)
        process(i,2) = process(i-1,2)*(1+ gold_real(i) );
    else 
        process(i,2) = process(i-1,2);
    end
    process(i,3) = process(i-1,3);
    today_money = sum(process(i,:));
    bit_fac = abs( Cvar(j,1)/(Cvar(j,1)+Cvar(j,2) ) );
    gold_fac = abs( Cvar(j,2)/(Cvar(j,1)+Cvar(j,2)) );

    if(gold_real(i)~=0)
    if(Cvar(j,3)<1)
        stock_money = today_money;
        process(i,1) = stock_money* bit_fac -abs(stock_money* bit_fac - process(i,1)) * BIT_RATE;
        process(i,2) = stock_money* gold_fac -abs(stock_money* bit_fac - process(i,1)) * gold_RATE;
        process(i,3) = 0 ;
    else
        stock_money = today_money * ( 1.01- Cvar(j,3)/maxvar ) ;    
        process(i,1) = stock_money* bit_fac -abs(stock_money* bit_fac - process(i,1)) * BIT_RATE;
        process(i,2) = stock_money* gold_fac -abs(stock_money* bit_fac - process(i,1)) * gold_RATE;
        process(i,3) = today_money- stock_money ;
    end
    else
        if( Cvar(j,3)<1)
        stock_money = today_money - process(i,2);
        process(i,1) = stock_money* bit_fac -abs(stock_money* bit_fac - process(i,1)) * BIT_RATE;
        process(i,3) =  stock_money - stock_money* bit_fac  ; 
        else 
         process(i,1) = process(i-1,1);
         process(i,2) = process(i-1,2);
         process(i,3) = process(i-1,3);
        end
    end
% % 

end
% disp("okok")
% %%
% figure;
% plot(W),
% title('the Value of the CVar');
% %% 
% figure
% 
% plot(process,LineWidth=1);hold on;
% legend('bitcoin',"Gold",'USD$');
% 
% xlabel('Time Number')
% ylabel('$')
% title("Beta = 0.96 annualized rate of return = %23.37");

tt = sum(process(1825,:));
profits = [profits,(tt/Cap).^0.25-1];

end

